package com.weijian.util;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订单相关分布式锁工具类
 * 专门用于订单创建时的防超卖场景
 * 
 * @author weijian
 */
@Component
public class OrderLockUtil {

    @Resource
    private RedisLockUtil redisLockUtil;

    private static final String ORDER_CREATE_LOCK = "order:create:";
    private static final String COURSE_STOCK_LOCK = "course:stock:";

    /**
     * 获取订单创建锁
     * 防止同一用户并发创建订单
     * 
     * @param userId 用户ID
     * @param courseId 课程ID
     * @return 锁标识，失败返回null
     */
    public String tryOrderCreateLock(Long userId, Long courseId) {
        String lockKey = ORDER_CREATE_LOCK + userId + ":" + courseId;
        return redisLockUtil.tryLock(lockKey, 5); // 5秒超时
    }

    /**
     * 释放订单创建锁
     */
    public boolean unlockOrderCreate(Long userId, Long courseId, String lockValue) {
        String lockKey = ORDER_CREATE_LOCK + userId + ":" + courseId;
        return redisLockUtil.unlock(lockKey, lockValue);
    }

    /**
     * 获取课程库存锁
     * 防止超卖的核心锁
     * 
     * @param courseId 课程ID
     * @return 锁标识，失败返回null
     */
    public String tryCourseStockLock(Long courseId) {
        String lockKey = COURSE_STOCK_LOCK + courseId;
        return redisLockUtil.tryLock(lockKey, 3); // 3秒超时
    }

    /**
     * 释放课程库存锁
     */
    public boolean unlockCourseStock(Long courseId, String lockValue) {
        String lockKey = COURSE_STOCK_LOCK + courseId;
        return redisLockUtil.unlock(lockKey, lockValue);
    }

    /**
     * 检查课程是否正在被购买
     * 用于前端提示
     */
    public boolean isCourseBeingPurchased(Long courseId) {
        String lockKey = COURSE_STOCK_LOCK + courseId;
        return redisLockUtil.isLocked(lockKey);
    }
}